package com.feige.controller;

import com.feige.utils.common.Base64;
import com.feige.constant.Constants;
import com.feige.result.AjaxResult;
import com.feige.utils.verifycode.GenerateVerifyCodeImg;
import com.feige.utils.redis.RedisUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
/**
 * 验证码操作处理
 *
 * @author feige
 */
@Api(tags = "生成验证码")
@RestController
@RequestMapping("/admin")
public class CaptchaController {

    @Resource
    private RedisUtils redisUtils;

    @Value("${captcha.isMath}")
    private Boolean isMath;

    /**
     * 生成验证码
     */
    @ApiOperation(value = "生成验证码")
    @GetMapping("/captcha_image")
    public AjaxResult getCode() throws IOException {
        ByteArrayOutputStream stream = null;
        // 唯一标识
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        if (isMath){
            //生成随机数字验证码
            Map<String, String> ve = GenerateVerifyCodeImg.generateArithmeticVerifyCode();
            redisUtils.set(verifyKey,ve.get("result"),Constants.CAPTCHA_CODE_EXPIRE);
            // 生成图片
            int w = 111, h = 36;
            stream = new ByteArrayOutputStream();
            GenerateVerifyCodeImg.generateImg(w, h, stream, ve.get("code"),isMath);
        }else {
            // 生成随机字串
            String verifyCode = GenerateVerifyCodeImg.generateVerifyCode(4);
            redisUtils.set(verifyKey,verifyCode,Constants.CAPTCHA_CODE_EXPIRE);
            // 生成图片
            int w = 111, h = 36;
            stream = new ByteArrayOutputStream();
            GenerateVerifyCodeImg.generateImg(w, h, stream, verifyCode,isMath);
        }
        try {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("uuid", uuid);
            ajax.put("img", Base64.encode(stream.toByteArray()));
            return ajax;
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        } finally {
            stream.close();
        }
    }
}
